/**
 * Created with IntelliJ IDEA.
 * Description:实现一个简单的 生产者 消费者 模型
 * User: rei
 * Date: 2025-11-05
 * Time: 10:36
 */
public class MyBlockingQueue {

    //数组
    private int[] elem;

    private int head;
    private int tail;
    private int size;

    public MyBlockingQueue(int capacity) {
        //初始化
        elem = new int[capacity];
        head = tail = 0;
        size = 0;

    }

    //先实现队列,然后再加 放的是尾
    public void put(int val) throws InterruptedException {
        //满了 就等待 唤醒之后重新判断条件,如果是if的话唤醒之后就直接执行后面操作了
        //只要wait在条件语句中 就用while重新判断
        synchronized (this) {
            while (size >= elem.length) {

                this.wait();


            }

            elem[tail] = val;
            tail++;
            //越界了就重头开始
            if (tail >= elem.length) {
                tail = 0;
            }

            size++;
            synchronized (this) {
                this.notifyAll();
            }
        }
    }

    //取出元素 取得是头
    public int take() throws InterruptedException {
        //空的 就等有人放入
        while (size == 0) {
            synchronized (this) {
                this.wait();
            }
        }
        int num = elem[head];

        head++;
        if (head >= elem.length) {
            head = 0;
        }
        size--;
        synchronized (this) {
            this.notifyAll();
        }
        return num;
    }
}
